package com.shitou.service;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.shitou.pojo.Group;
import com.shitou.pojo.User;

public class ShiroDbRealm extends AuthorizingRealm{

	@Resource
	private UserService userService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		
		String name =  (String) principal.fromRealm(getName()).iterator().next();
		
		User user = userService.findByName(name);
		
		if(user != null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			info.setRoles(user.getGroupNameSet());
			for(Group g : user.getGroupList()) {
				info.addStringPermissions(g.getPermissionStringList());
				return info;
			}
		}
		
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken myToken = (UsernamePasswordToken) token;
		
		User user = userService.findByName(myToken.getUsername());
		
		if(user != null) {
			return new SimpleAuthenticationInfo(user.getName(),user.getPassword(),getName());
		}
		
		return null;
	}

}
